package com.gmrz.uas.plugin.sm2;

import org.bouncycastle.util.Arrays;

import java.io.IOException;
import java.io.OutputStream;
import java.security.SignatureException;

/**
 * Created by zhangchao on 4/12/18.
 */
public class SM2SignatureOutputStream extends OutputStream {

    byte[] privKey;
    byte[] signature;
    byte[] sourceData;

    private byte[] userId;

    public SM2SignatureOutputStream(byte[] key) {
        this.privKey = key;
    }

    public void write(byte[] var1, int off, int len) throws IOException {
        try {
            if(var1==null || var1.length < off + len){
                return;
            }
            byte[] tmp = new byte[len];
            for(int i=0;i<len;i++){
                tmp[i] = var1[i+off];
            }
            if(sourceData != null){
                sourceData = Arrays.concatenate(sourceData,tmp);
            }else{
                sourceData = tmp;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void write(byte[] var1) throws IOException {
        write(var1,0,var1.length);
    }

    public void write(int var1) throws IOException {
        byte[] bytes =  new byte[] {
                (byte) ((var1 >> 24) & 0xFF),
                (byte) ((var1 >> 16) & 0xFF),
                (byte) ((var1 >> 8) & 0xFF),
                (byte) (var1 & 0xFF)
        };
        write(bytes,0,bytes.length);
    }

    public byte[] getSignature() throws SignatureException {
        try {
            signature = SM2Utils.sign(SM2Utils.DEFAULT_USERID,privKey,sourceData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return signature;
    }
}